#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直观显示日本邮政EMS运费价格
按区域和国家分类展示
"""

import json
import pandas as pd
from typing import Dict, List

def load_ems_data(filename: str = "japanpost_ems_prices.json") -> List[Dict]:
    """加载EMS运费数据"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data
    except Exception as e:
        print(f"❌ 加载数据失败：{e}")
        return []

def display_zone_prices(data: List[Dict]):
    """按区域显示运费价格"""
    print("🌍 日本邮政EMS运费价格表（按区域分类）")
    print("=" * 80)
    
    # 区域信息
    zones = {
        "第1区": "中国、韩国、台湾",
        "第2区": "亚洲（中国、韩国、台湾除外）",
        "第3区": "大洋洲、加拿大、墨西哥、中近东、欧洲",
        "第4区": "美国（包括关岛等海外领土）",
        "第5区": "中南美（墨西哥除外）、非洲"
    }
    
    # 选择几个重要重量进行展示
    key_weights = [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0]
    
    for zone, region_name in zones.items():
        print(f"\n📍 {zone}: {region_name}")
        print("-" * 60)
        print(f"{'重量':<12} {'价格(日元)':<15} {'备注'}")
        print("-" * 60)
        
        for weight in key_weights:
            # 找到最接近的重量
            closest_item = None
            min_diff = float('inf')
            
            for item in data:
                if abs(item['weight'] - weight) < min_diff:
                    min_diff = abs(item['weight'] - weight)
                    closest_item = item
            
            if closest_item and zone in closest_item['prices']:
                price = closest_item['prices'][zone]
                weight_desc = closest_item['weight_text']
                print(f"{weight_desc:<12} {price:>8,}        {weight}kg")
        
        print()

def display_country_comparison(data: List[Dict]):
    """显示主要国家/地区的价格对比"""
    print("🏛️  主要国家/地区EMS运费对比")
    print("=" * 80)
    
    # 选择几个重要重量
    key_weights = [0.5, 1.0, 2.0, 5.0, 10.0, 20.0]
    
    print(f"{'重量':<12} {'中国/韩国/台湾':<18} {'亚洲其他':<18} {'欧洲/大洋洲':<18} {'美国':<18} {'中南美/非洲':<18}")
    print("-" * 100)
    
    for weight in key_weights:
        # 找到最接近的重量
        closest_item = None
        min_diff = float('inf')
        
        for item in data:
            if abs(item['weight'] - weight) < min_diff:
                min_diff = abs(item['weight'] - weight)
                closest_item = item
        
        if closest_item:
            weight_desc = closest_item['weight_text']
            prices = closest_item['prices']
            
            zone1 = f"{prices.get('第1区', 0):,}"
            zone2 = f"{prices.get('第2区', 0):,}"
            zone3 = f"{prices.get('第3区', 0):,}"
            zone4 = f"{prices.get('第4区', 0):,}"
            zone5 = f"{prices.get('第5区', 0):,}"
            
            print(f"{weight_desc:<12} {zone1:<18} {zone2:<18} {zone3:<18} {zone4:<18} {zone5:<18}")
    
    print()

def display_weight_categories(data: List[Dict]):
    """按重量类别显示价格"""
    print("📦 按重量类别显示EMS运费")
    print("=" * 80)
    
    # 重量类别
    weight_categories = [
        (0.5, "轻量级 (≤500g)"),
        (1.0, "小件 (≤1000g)"),
        (2.0, "中件 (≤2000g)"),
        (5.0, "重件 (≤5000g)"),
        (10.0, "大件 (≤10000g)"),
        (20.0, "超大件 (≤20000g)"),
        (30.0, "极重件 (≤30000g)")
    ]
    
    for target_weight, category_name in weight_categories:
        print(f"\n📋 {category_name}")
        print("-" * 50)
        
        # 找到最接近的重量
        closest_item = None
        min_diff = float('inf')
        
        for item in data:
            if abs(item['weight'] - target_weight) < min_diff:
                min_diff = abs(item['weight'] - target_weight)
                closest_item = item
        
        if closest_item:
            weight_desc = closest_item['weight_text']
            prices = closest_item['prices']
            
            print(f"重量: {weight_desc}")
            print(f"第1区 (中国/韩国/台湾): {prices.get('第1区', 0):,} 日元")
            print(f"第2区 (亚洲其他): {prices.get('第2区', 0):,} 日元")
            print(f"第3区 (欧洲/大洋洲): {prices.get('第3区', 0):,} 日元")
            print(f"第4区 (美国): {prices.get('第4区', 0):,} 日元")
            print(f"第5区 (中南美/非洲): {prices.get('第5区', 0):,} 日元")

def display_price_trends(data: List[Dict]):
    """显示价格趋势分析"""
    print("\n📈 EMS运费价格趋势分析")
    print("=" * 80)
    
    # 分析价格趋势
    zones = ["第1区", "第2区", "第3区", "第4区", "第5区"]
    zone_names = ["中国/韩国/台湾", "亚洲其他", "欧洲/大洋洲", "美国", "中南美/非洲"]
    
    print("💰 各区域价格区间分析:")
    print("-" * 60)
    
    for i, zone in enumerate(zones):
        prices = [item['prices'].get(zone, 0) for item in data if zone in item['prices']]
        if prices:
            min_price = min(prices)
            max_price = max(prices)
            avg_price = sum(prices) / len(prices)
            
            print(f"{zone_names[i]:<18}: 最低 {min_price:,} 日元, 最高 {max_price:,} 日元, 平均 {avg_price:,.0f} 日元")
    
    print("\n📊 价格梯度分析:")
    print("-" * 60)
    
    # 选择几个重量点进行分析
    analysis_weights = [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0]
    
    for weight in analysis_weights:
        # 找到最接近的重量
        closest_item = None
        min_diff = float('inf')
        
        for item in data:
            if abs(item['weight'] - weight) < min_diff:
                min_diff = abs(item['weight'] - weight)
                closest_item = item
        
        if closest_item:
            weight_desc = closest_item['weight_text']
            prices = closest_item['prices']
            
            print(f"\n{weight_desc} ({int(weight * 1000)}g):")
            for zone, zone_name in zip(zones, zone_names):
                if zone in prices:
                    print(f"  {zone_name}: {prices[zone]:,} 日元")

def main():
    """主函数"""
    print("🚀 日本邮政EMS运费价格展示系统")
    print("=" * 80)
    
    # 加载数据
    data = load_ems_data()
    if not data:
        print("❌ 无法加载数据")
        return
    
    print(f"✅ 成功加载 {len(data)} 条运费数据")
    
    # 1. 按区域显示价格
    display_zone_prices(data)
    
    # 2. 国家/地区价格对比
    display_country_comparison(data)
    
    # 3. 按重量类别显示
    display_weight_categories(data)
    
    # 4. 价格趋势分析
    display_price_trends(data)
    
    print("\n🎉 价格展示完成！")
    print("\n💡 提示:")
    print("  - 第1区价格最低，适合中国、韩国、台湾地区")
    print("  - 第2区价格适中，适合亚洲其他地区")
    print("  - 第3区价格较高，适合欧洲、大洋洲等远距离地区")
    print("  - 第4区价格最高，适合美国等超远距离地区")
    print("  - 第5区价格较高，适合中南美、非洲等地区")

if __name__ == "__main__":
    main()
